<template>
    <div>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="name" label="图片名称" width="200"></el-table-column>
            <el-table-column prop="url" label="图片预览" width="200">
                <template slot-scope="scope">
                    <el-image style="width: 100px; height: 100px" :src="scope.row.url"
                        :preview-src-list="[scope.row.url]">
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column prop="url" label="图片地址" width="400"></el-table-column>
            <el-table-column prop="clickCount" label="点击次数" width="200"></el-table-column>
            <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>
        <div class="image-upload-container">
            <el-upload ref="upload" :limit="limit" accept=".jpg, .png" :action="upload.url" :headers="upload.headers"
                :file-list="upload.fileList" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading"
                    @click="submitUpload">上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </div>
        <el-dialog title="编辑图片" :visible.sync="dialogVisible" width="30%">
            <el-form :model="editForm">
                <el-form-item label="图片名称">
                    <el-input v-model="editForm.name"></el-input>
                </el-form-item>
                <el-form-item label="图片地址">
                    <el-input v-model="editForm.url"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { query, add } from '@/api/erp/promotion'

export default {
    name: 'ImageUpload',
    props: {
        // 上传限制
        limit: {
            type: Number,
            default: 5
        }
    },
    data() {
        return {
            tableData: [], 
            dialogVisible: false, 
            editForm: {
                id: '',
                name: '',
                url: '',
                clickCount: 0
            },
            editIndex: -1, 
            upload: {
                // 是否禁用上传
                isUploading: false,
                // 设置上传的请求头部
                headers: { Authorization: getToken() },
                // 上传的地址
                url: window.location.href.split('/').slice(0, 3).join('/') + '/api/common/uploadImage',
                // url: process.env.VUE_APP_BASE_API + '/api/common/uploadImage',
                // 上传的文件列表
                fileList: []
            }
        }
    },
    created() {
        this.loadImageList();
        // console.log('process.env.VUE_APP_BASE_API',process.env.VUE_APP_BASE_API);
    },
    methods: {
        // 加载图片列表
        loadImageList() {
            query({ key: 'home_banner' }).then(res => {
                if (res.status === 200 && res.data) {
                    try {
                        let images = JSON.parse(res.data.content[0].value) || [];
                        
                        this.tableData = images;
                    } catch (e) {
                        console.log('解析图片数据失败', e);
                        this.tableData = [];
                    }
                } else {
                    this.tableData = [];
                }
            }).catch(err => {
                console.log('加载图片列表失败', err);
                this.tableData = [];
            });
        },

        // 提交上传
        submitUpload() {
            this.$refs.upload.submit();
        },
        
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.isUploading = false;
            if (response.status === 200) {
                console.log(response.data);
                
                query({ key: 'home_banner' }).then(queryRes => {
                    let existingImages = [];
                    if (queryRes.status === 200 && queryRes.data) {
                        console.log('queryRes.data',queryRes.data.content[0].value);
                        try {
                            existingImages =JSON.parse(queryRes.data.content[0].value) || [];
                                           console.log('existingImages',existingImages);
                        } catch (e) {
                            console.log('解析现有图片数据失败', e);
                            existingImages = [];
                        }
                    }                   
                    const newImage = {
                        id: response.data.id,
                        name: file.name,
                        url: response.data.path,
                        clickCount: 0
                    };
                    console.log('existingImages1',existingImages);
                    console.log('newImage',newImage);
                    existingImages.push(newImage);
                    console.log('existingImages2',existingImages);
                    
                    const requestBody = {
                        id: 18,
                        key: 'home_banner',
                        type: 1,
                        value: JSON.stringify(existingImages)  
                    };
                    
                    //调用add方法保存图片地址
                    add(requestBody).then(res => {
                        if (res.status === 200) {
                            this.$message.success('上传并保存成功');
                            this.$emit('upload-success', response.data);
                            this.loadImageList();
                        } else {
                            this.$message.error(res.msg || '保存图片信息失败');
                        }
                    }).catch(err => {
                        this.$message.error('保存图片信息失败');
                        console.error(err);
                    });
                }).catch(queryErr => {
                    console.log('查询现有图片失败', queryErr);
                    // 如果查询失败，仍然尝试保存新图片
                    const requestBody = {
                        id: 18,
                        key: 'home_banner',
                        type: 1,
                        value: JSON.stringify([{
                            name: file.name,
                            url: response.data.path,
                            clickCount: 0
                        }])
                    };
                    
                    add(requestBody).then(res => {
                        if (res.status === 200) {
                            this.$message.success('上传并保存成功');
                            this.$emit('upload-success', response.data);
                            this.loadImageList();
                        } else {
                            this.$message.error(res.msg || '保存图片信息失败');
                        }
                    }).catch(err => {
                        this.$message.error('保存图片信息失败');
                        console.error(err);
                    });
                });
            } else {
                this.$message.error(response.msg || '上传失败');
            }
        },

        // 删除图片
        handleDelete(index) {
            this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 从表格数据中删除图片
                this.tableData.splice(index, 1);

                const requestBody = {
                    id: 18,
                    key: 'home_banner',
                    type: 1,
                    value: JSON.stringify(this.tableData)
                };
                
                // 保存更新后的图片列表
                add(requestBody).then(res => {
                    if (res.status === 200) {
                        this.$message.success('删除成功');
                    } else {
                        this.$message.error(res.msg || '删除失败');
                        this.loadImageList();
                    }
                }).catch(err => {
                    this.$message.error('删除失败');
                    console.error(err);
                    this.loadImageList();
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 编辑图片
        handleEdit(index, row) {
            this.editIndex = index;
            this.editForm = { ...row };
            this.dialogVisible = true;
        },

        // 保存编辑
        saveEdit() {
            // 更新表格数据
            this.tableData.splice(this.editIndex, 1, { ...this.editForm });

            const requestBody = {
                id: 18,
                key: 'home_banner',
                type: 1,
                value: JSON.stringify(this.tableData)
            };

            // 保存更新后的图片列表
            add(requestBody).then(res => {
                if (res.status === 200) {
                    this.$message.success('编辑成功');
                    this.dialogVisible = false;
                } else {
                    this.$message.error(res.msg || '编辑失败');
                    this.loadImageList(); 
                }
            }).catch(err => {
                this.$message.error('编辑失败');
                console.error(err);
                this.loadImageList(); 
            });
        },

    }
}
</script>

<style scoped>
.image-upload-container {
    padding: 20px;
}
</style>
